﻿using System;
using System.Collections.Generic;
using Generator.Selections.DataBase;
using Generator.Selections.DataDictionary;

namespace Generator.Selections.Repository
{
    class TableRepository
    {
        internal List<SelectedTable> GetTablesByOwner(string tableOwner)
        {
            var result = new List<SelectedTable>();

            try
            {
                ConnectionHandler.Instance.Connection.Open();
                GetTables(tableOwner, result);
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.ToString());
            }
            finally
            {
                ConnectionHandler.Instance.Connection.Close();
            }

            return result;
        }

        private static void GetTables(string tableOwner, List<SelectedTable> result)
        {
            using (var cmd = DataDictionaryCommands.GetSelectTableByOnwerCommand(tableOwner))
            {
                using (var rdr = cmd.ExecuteReader())
                {
                    while (rdr.Read())
                    {
                        var tableName = (rdr[0].ToString());
                        var table = new SelectedTable(tableName);
                        result.Add(table);
                    }
                }
            }
        }

        internal List<SelectedTable> GetTablesByNameLike(string tableNameLike)
        {
            var result = new List<SelectedTable>();

            try
            {
                ConnectionHandler.Instance.Connection.Open();
                using (var cmd = DataDictionaryCommands.GetSelectTableByNameCommand(tableNameLike))
                {
                    using (var rdr = cmd.ExecuteReader())
                    {
                        if (rdr == null) return result;

                        while (rdr.Read())
                        {
                            var tableName = (rdr[0].ToString());
                            var table = new SelectedTable(tableName);
                            result.Add(table);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.ToString());
            }
            finally
            {
                ConnectionHandler.Instance.Connection.Close();
            }

            return result;
        }
    }
}
